<template>
  <div class="resourceIssue-container" v-loading="issueData.loading">
    <div class="header">成果发布</div>
    <div class="body">
      <div class="bodyLeft">
        <el-form
          ref="rformRef"
          :model="issueData"
          label-width="120px"
          size="default"
          :rules="rules"
        >
          <el-form-item label="标题" prop="title">
            <el-input
              v-model="issueData.title"
              placeholder="请输入成果标题"
              clearable
            />
          </el-form-item>

          <el-form-item label="成果分类" prop="typeid">
            <el-select
              v-model="issueData.typeid"
              placeholder="请选择成果分类"
              filterable
              clearable
            >
              <el-option
                v-for="item in issueData.achievementType"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="简介" prop="abstract">
            <el-input
              v-model="issueData.abstract"
              type="textarea"
              :autosize="{ minRows: 3, maxRows: 6 }"
              placeholder="请输入成果简介(120字以内)"
              clearable
            />
          </el-form-item>

          <el-form-item label="成果链接" prop="achievementlink">
            <el-input
              v-model="issueData.achievementlink"
              placeholder="请输入成果链接"
              clearable
            />
          </el-form-item>
        </el-form>
      </div>
      <div class="bodyRight">
        <label class="upload-label">封面</label>
        <div
          class="imgupload"
          @mouseleave="myhidden = true"
          @mouseenter="myhidden = false"
        >
          <el-upload
            class="upload-demo"
            drag
            :limit="1"
            :on-preview="handlePictureCardPreview"
            :on-remove="remove1"
            :on-change="handleChange1"
            :auto-upload="false"
            v-if="!myFlag"
            v-loading="mygo"
          >
            <el-icon class="el-icon--upload">
              <upload-filled />
            </el-icon>
            <div class="el-upload__text">
              Drop file here or <em>click to upload</em>
            </div>
          </el-upload>
          <div v-else class="fengmain">
            <img :src="issueData.posterlink" />
            <div
              class="fengmainlayout"
              :style="{
                opacity: myhidden ? 0 : 1,
              }"
            >
              <el-icon @click="remove1">
                <Delete />
              </el-icon>
              <el-icon @click="handlePictureCardPreview">
                <Plus />
              </el-icon>
            </div>
          </div>
        </div>
        <div class="fujian">
          <el-upload
            ref="uploadp"
            class="upload-demo"
            :auto-upload="false"
            :limit="1"
            :on-exceed="handleExceedp"
            :on-change="handleChange2"
            :on-remove="remove2"
            :file-list="orientFileList.fujian"
          >
            <el-button type="primary" :icon="Upload">上传成果附件</el-button>
          </el-upload>
        </div>
      </div>
      <el-dialog v-model="dialogVisible">
        <img
          :src="issueData.posterlink"
          alt="Preview Image"
          style="width: 100%"
        />
      </el-dialog>
    </div>
    <el-button
      round
      type="primary"
      class="fabu"
      @click="submitForm(rformRef)"
      :loading="issueData.loading"
    >
      {{ issueData.status === 2 ? '更新' : '发布' }}
    </el-button>
  </div>
</template>

<script setup>
import { Delete, Plus, Upload, UploadFilled } from '@element-plus/icons-vue'
import { useRoute, useRouter } from 'vue-router'
import { computed, onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import qiniu from '../../utils/qiniu'
import Cookies from 'js-cookie'
import axios from '@/utils/Axios.ts'
import Base from '@/api/base.js'
import { getAchievementIssue } from '@/api/achievementIssue'

const myhidden = ref(true)
const mygo = ref(false)
const route = useRoute()
const router = useRouter()
const issueData = reactive({
  status: 1, // 默认1数据添加状态，2数据更新状态,
  achievementType: [],
  loading: false,
  progress: 0,
  coverLoading: false, // 封面图上传进度
  delCoverLoading: false, // 删除封面图
  delCoverStatus: false, // 是否删除封面图的状态
  attachmentStatus: false, // 是否有附件
  attachmentLoading: false, // 上传附件的进度
  date: new Date(), // 成果发布日期
  myFile1: null,
  myFile2: null,
  posterlink: null, // 封面图的cdn地址
  attachment: null, // 附件的cdn地址
  id: route.query.id || 0, // 成果Id
  title: null,
  achievementlink: null,
  abstract: null,
  typeid: null,
})
const myFlag = computed(() => issueData.posterlink)
const rformRef = ref(null)
const rules = reactive({
  title: [{ required: true, message: '请输入成果标题', trigger: 'blur' }],
  typeid: [{ required: true, message: '请选择成果分类', trigger: 'change' }],
  abstract: [{ required: true, message: '请输入成果简介', trigger: 'blur' }],
  achievementlink: [{ required: false, trigger: 'blur' }],
})
const orientFileList = reactive({
  fenmian: [],
  fujian: [],
})
const dialogVisible = ref(false)
const dialogImageUrl = ref('')
const handlePictureCardPreview = () => {
  dialogVisible.value = true
}

async function handelIssue() {
  issueData.loading = true

  try {
    // 上传附件
    if (issueData.myFile2) {
      await qiniu(issueData.myFile2)
        .then(res => {
          issueData.attachment = res.key
        })
        .catch(() => {
          throw new Error('附件上传失败')
        })
    } else {
      issueData.attachment = ''
    }

    // 上传封面图
    if (issueData.myFile1) {
      await qiniu(issueData.myFile1)
        .then(res => {
          issueData.posterlink = 'http://img.pzhuweb.cn/' + res.key
        })
        .catch(() => {
          throw new Error('封面图上传失败')
        })
    }

    let date = new Date(issueData.date)
    const data = {
      id: issueData.id,
      userId: Cookies.get('yourStuNum'),
      title: issueData.title,
      typeId: issueData.typeid,
      introduction: issueData.abstract,
      achievementlink: issueData.achievementlink,
      status: issueData.status,
      posterlink: "http://img.pzhuweb.cn/"+issueData.posterlink,
      attachment: "http://img.pzhuweb.cn/"+issueData.attachment,
    }

    const res = await axios.post(`achievementIssue/updateAchievement/${data.id}`, data)
    const result = res

    if (result.success) {
      issueData.loading = false
      ElMessage({
        showClose: true,
        message:  '成果更新成功',
        type: 'success',
      })
      // 延迟跳转，让用户看到成功提示
      setTimeout(() => {
        router.push('/user/ac')
      }, 1000)
    } else {
      issueData.loading = false
      throw new Error(result.message || '发布失败')
    }
  } catch (error) {
    issueData.loading = false
    ElMessage({
      showClose: true,
      message: error.message || '发布失败，请重试',
      type: 'error',
    })
    throw error
  }
}

function remove1() {
  orientFileList.fenmian = []
  issueData.posterlink = ''
  issueData.url = ''
  issueData.myFile1 = null
}

function remove2() {
  orientFileList.fujian = []
}

const submitForm = async formEl => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (!valid) {
      console.log('error fields: ', fields)
      ElMessage({
        showClose: true,
        message: '请完善成果信息',
        type: 'error',
      })
      return
    }

    if (!issueData.myFile1 && !issueData.posterlink) {
      ElMessage({
        showClose: true,
        message: '请上传封面图片',
        type: 'error',
      })
      return
    }

    try {
      await handelIssue()
    } catch (error) {
      console.error('提交失败:', error)
      ElMessage({
        showClose: true,
        message: '提交失败，请重试',
        type: 'error',
      })
    }
  })
}

onMounted(async () => {
  // 获取成果分类
  axios.get('/backapi/achievementTypes').then(res => {
    issueData.achievementType = res.achievementTypes
  })

  // 如果有id参数，则获取成果详情进行数据回显
  if (issueData.id && issueData.id !== 0) {
    try {
      issueData.loading = true
      const res = await getAchievementIssue({ id: issueData.id })
      if (res.success) {
        const data = res.data
        // 回显基本信息
        issueData.title = data.achievement.title
        issueData.typeid = data.achievement.typeId
        issueData.abstract = data.achievement.introduction
        issueData.achievementlink = data.achievement.achievementlink

        // 回显封面图
        if (data.achievement.posterlink) {
          issueData.posterlink = data.achievement.posterlink
        }

        // 回显附件信息
        if (data.achievement.attachment) {
          issueData.attachment = data.achievement.attachment
          // 构造附件文件列表用于显示
          orientFileList.fujian = [
            {
              name: '已上传的附件',
              url: data.attachment,
            },
          ]
        }
      } else {
        ElMessage({
          showClose: true,
          message: res.message || '获取成果信息失败',
          type: 'error',
        })
      }
    } catch (error) {
      console.error('获取成果详情失败:', error)
      ElMessage({
        showClose: true,
        message: '获取成果信息失败，请重试',
        type: 'error',
      })
    } finally {
      issueData.loading = false
    }
  }
})

const uploadf = ref(null)
const uploadp = ref(null)

function handleChange1(file1) {
  let url = ''
  mygo.value = true
  if (window.createObjectURL !== undefined) {
    url = window.createObjectURL(file1.raw)
  } else if (window.URL !== undefined) {
    url = window.URL.createObjectURL(file1.raw)
  } else if (window.webkitURL !== undefined) {
    url = window.webkitURL.createObjectURL(file1.raw)
  }
  if (url != null || url !== undefined || url !== '') {
    mygo.value = false
    issueData.posterlink = url
  }
  issueData.myFile1 = file1
}

function handleChange2(file2) {
  issueData.myFile2 = file2
}

function handleExceedp(files, uploadFiles) {
  ElMessage.warning(
    `最多只能上传1个文件，您选择了${files.length}个文件，总共${
      files.length + uploadFiles.length
    }个文件`
  )
  uploadp.value?.clearFiles()
  const file = files[0]
  uploadp.value?.handleStart(file)
  issueData.myFile2 = file
  issueData.attachment = ''
}
</script>
<style lang="less">
.bodyRight .el-upload__tip {
  text-align: center;
}

.bodyRight .el-upload {
  margin: 0 auto;
}

@media (max-width: 800px) {
  .bodyLeft {
    .el-form-item__label {
      width: 20px !important;
    }

    .el-form-item__content {
      margin-left: 5px !important;
    }
  }

  .bodyRight {
    .el-upload-list {
      width: 100%;
    }
  }
}
</style>
<style scoped lang="less">
.resourceIssue-container {
  width: 1200px;
  background-color: #fff;
  border-radius: 10px;
  margin: 80px auto 20px;
  padding: 25px;

  .header {
    color: rgba(0, 0, 0, 0.65);
    width: 100%;
    height: 80px;
    font-size: 30px;
    font-weight: 600;
    line-height: 80px;
  }

  .fabu {
    display: block;
    width: 200px;
    padding: 5px 0;
    margin: 0 auto;
  }

  .body {
    width: 100%;
    display: flex;
  }

  .bodyLeft {
    width: 50%;

    .myType {
      margin: 10px 5px;
    }
  }

  .bodyRight {
    width: 50%;
    display: flex;
    justify-content: space-around;
    align-items: center;
    flex-direction: column;

    .fujian {
      margin-top: 10px;
      width: 100%;

      .fujianlist {
        width: 100%;
        height: 30px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        transition: all 0.5s;
        color: #606266;
        line-height: 18px;
        padding: 0 10px 0;

        .fujianclose {
          opacity: 0;
          cursor: pointer;
        }

        .item a {
          color: #606266;
          margin-left: 10px;
          font-size: 20px;
        }

        .item:hover a {
          color: #48a2ff;
        }

        &:hover {
          background-color: #f5f7fa;

          .fujianclose {
            opacity: 1;
          }
        }
      }
    }

    .upload-label {
      display: block;
      text-align: left;
      margin-bottom: 10px;
      font-weight: bold;
      color: #606266;
    }

    .imgupload {
      width: 80%;
      // height: 230px;
      .fengmain {
        cursor: pointer;
        width: 100%;
        height: 230px;
        position: relative;
        border-radius: 10px;
        overflow: hidden;

        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }

        .fengmainlayout {
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          background-color: rgba(0, 0, 0, 0.5);
          opacity: 0;
          transition: opacity 0.3;
          display: inline-flex;
          justify-content: space-around;
          align-items: center;
          color: #fff;
          font-size: 25px;
        }
      }
    }
  }
}

@media (max-width: 900px) {
  .resourceIssue-container {
    width: 100%;

    .header {
      font-size: 20px;
    }

    .body {
      flex-direction: column-reverse;
    }

    .bodyLeft {
      width: 100%;

      .fabu {
        margin-left: 20px;
      }
    }

    .bodyRight {
      padding-bottom: 50px;
      width: 100%;
    }
  }
}
</style>
